package edu.hawaii.duedates.library;

import com.meterware.httpunit.GetMethodWebRequest;
import com.meterware.httpunit.HttpUnitOptions;
import com.meterware.httpunit.WebConversation;
import com.meterware.httpunit.WebForm;
import com.meterware.httpunit.WebLink;
import com.meterware.httpunit.WebRequest;
import com.meterware.httpunit.WebResponse;

/**
 * This class is built for actions related to the Hawaii State Library system. It is also implements
 * the Lender interface. Must have login and getInfo.
 * 
 * @author John Ly
 * @author John Zhou
 */
public class HawaiiState extends Lender {
  /**
   * Attempts to login to the Hawaii State Library System.
   * 
   * @param id The Hawaii library id barcode.
   * @param password The password (last four digits of your phone number).
   * @return The WebConversation after logging in.
   * @throws Exception If errors occur while logging in.
   */
  public WebConversation login(String id, String password) throws Exception {
    try {
      String url = "http://www.librarieshawaii.org/";
      // Website has bogus JavaScript code.
      HttpUnitOptions.setExceptionsThrownOnScriptError(false);
      // create the conversation object which will maintain state for us
      WebConversation conversation = new WebConversation();
      WebRequest request = new GetMethodWebRequest(url);
      WebResponse response = conversation.getResponse(request);
      WebLink link = response.getLinkWith("My Account");
      link.click();
      response = conversation.getCurrentPage();
      WebForm form = response.getForms()[0];
      form.setParameter("sec1", "0011429495");
      form.setParameter("sec2", "3845");
      form.submit();
      return conversation;
    }
    catch (Exception e) {
      throw new Exception("Error while logging in to Hawaii State Library", e);
    }
  }

  /**
   * Gets info from the Hawaii State Library site.
   * 
   * @param hiStateId The barcode number from the library card.
   * @param hiStatePassword The password (normally the last four digits of your phone number).
   * @return A string providing information about checked out books.
   * @throws Exception If problems occur getting the information.
   */
  public String getInfo(String hiStateId, String hiStatePassword) throws Exception {
    try {
      WebConversation conversation = this.login(hiStateId, hiStatePassword);
      WebResponse response = conversation.getCurrentPage();
      WebLink link = response.getLinkWith("Items Out");
      link.click();
      response = conversation.getCurrentPage();
      boolean noBooksOut = response.getText().contains("Checked Out: 0");
      // TO DO figure out how to get book info
      return (noBooksOut) ? "No items checked out" : "At least one item checked out.";
    }
    catch (Exception e) {
      throw new Exception("Error getting Hawaii State Library info", e);
    }
  }

}
